//
//  JAPhotoViewerController.swift
//  JAWeiBo
//
//  Created by Arvin on 17/4/9.
//  Copyright © 2017年 Arvin. All rights reserved.
//

import UIKit
import SDWebImage

class JAPhotoViewerController: UIViewController {
    
    ///scrollView
    lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView(frame: screenBounds)
        return scrollView
    }()
    
    ///imageView
    lazy var imageView: UIImageView = UIImageView()
    
    ///当前需要展示的图片的index
    var index: Int = 0
    
    ///图片的url数组
    var pic_urls: [String] = []
    
    ///重载构造函数
    init(index: Int, pic_urls: [String]) {
        super.init(nibName: nil, bundle: nil)
        self.index = index
        self.pic_urls = pic_urls
    }
    
    /// 一旦重载UIView或者UIViewController的构造函数, 则必须实现该方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white
        
//         print("第\(index)张图片, url是\(pic_urls[index])")
        
         setupUI()
        
    }
}

extension JAPhotoViewerController {
    func setupUI () {
        
        self.view.addSubview(scrollView)
        scrollView.addSubview(imageView)
        
        //下载并展示图片
        let url = URL(string: pic_urls[index])
        SDWebImageManager.shared().loadImage(with: url!, options: [], progress: nil) { (image, _, _, _, _, _) in
            if let image = image {
                
                //先给imageView赋值
                self.imageView.image = image
                let size = image.size
                
                //将图片调整和屏幕一样的宽度
                //新高/新宽 = 原高/原宽
                let newWidth = screenWidh
                let newHeight = size.height * newWidth / size.width
                let newSize = CGSize(width: newWidth, height: newHeight)
                
                //设置imageView的frame
                let frame = CGRect(origin: CGPoint.zero, size: newSize)
                self.imageView.frame = frame
                
                //如果调整好图片,高度小于屏幕的高度,则居中显示
                if newHeight <= screenHeight {
                    self.imageView.center = self.scrollView.center
                } else {
                    self.scrollView.contentSize = newSize
                }
            }
        }
    }
}
